import { Provide,Inject } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Not, Repository } from 'typeorm';
import { AppVersionEntity } from '../entity/version';
import { DictInfoEntity } from '../../dict/entity/info';
import { DictInfoService } from '../../dict/service/info';
import * as semver from 'semver';

/**
 * 应用版本
 */
@Provide()
export class AppVersionService extends BaseService {
  @InjectEntityModel(AppVersionEntity)
  appVersionEntity: Repository<AppVersionEntity>;

  @InjectEntityModel(DictInfoEntity)
  DictInfoEntity: Repository<DictInfoEntity>;

  @Inject()
  dictInfoService: DictInfoService

  /**
   * 检查更新
   * @param version
   */
  async check(version: string, type = 0, brand: string) {
    const info = await this.appVersionEntity.findOneBy({ type, status: 1 });
    // 判断是不是大于整包更新的版本 如果是 就热更新  如果不是 就跳转到应用商店更新
    if (info) {
      if (semver.gt(info.package, version)) {
        const versionStore = await this.dictInfoService.data(["version"]);
        let temp
        if(brand=='ios'){
          temp = versionStore['version'].find(item => item.name == 'ios')
        }
        let url
        if (temp) {
          url = temp.value
        } else {
          url = versionStore['version'].find(item => item.name == 'h5').value
        }
        info.url = url
        return info
      } else {
        if (info && semver.gt(info.version, version)) {
          info.hotUpdate = 1
          return info;
        }
      }
    }
    return
  }
  /**
   * 修改之后
   * @param data
   * @param type
   */
  async modifyAfter(data: any, type: 'add' | 'update' | 'delete') {
    if (type == 'add' || type == 'update') {
      const info = await this.appVersionEntity.findOneBy({ id: data.id });
      if (info.status == 1) {
        // 将其他的版本设置为禁用
        await this.appVersionEntity.update(
          { type: info.type, id: Not(info.id) },
          { status: 0 }
        );
      }
    }
  }
}
